//
//  KHomePageViewController.m
//  DrugPin
//
//  Created by guohe on 2018/9/7.
//  Copyright © 2018年 outang. All rights reserved.
//
#import "KNavigationSelectView.h"
#import "KRedEnvelopeTableViewCell.h"
#import "KHomePageViewController.h"
#import "KBannerHeadTableViewCell.h"

#import "KRedEnvelopeModel.h"
#import "KRedEnvelopeDataListModel.h"

@interface KHomePageViewController ()<UITableViewDelegate,UITableViewDataSource>{
    KRedEnvelopeTableViewCell *cell; //封装的cell
    int flag;
}
// 导航栏
@property (nonatomic, strong)KNavigationSelectView *navigationSelectView;
// 底层tableView
@property (nonatomic, strong)UITableView *mainTable;
// mainTable 的headView
@property (nonatomic, strong)KBannerHeadTableViewCell *headView;
@end

@implementation KHomePageViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    flag = 0;
    [self setUpUI];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KRandomColor;
    [self loadDataWithAD];
    [self loadData];
}

#pragma mark - 红包活动接口请求
-(void)loadData{
    [SVProgressHUD show];
    NSDictionary *parameters = @{
                                 @"_appid" : @"103",
                                 @"_code" : [KUserLoginModel shareInstance].Code ? [KUserLoginModel shareInstance].Code : [KWXLoginUserListModel shareInstance].Code,
                                 @"sType": @"100301",//100301:竞赛红包
                                 @"Keyword":@"", //搜索框关键字
                                 @"PageIndex":@"1",
                                 @"PageSize":@"20"
                                 };
    //POST /Activity/GetActivityList 获取销售活动列表
    [[NetworkSingleton sharedManager]POSTdata:parameters Path:@"activity/getactivitylist" successBlock:^(id responseBody) {
        
        BaseModel *baseModel = [BaseModel mj_objectWithKeyValues:responseBody];
        if (baseModel.code != 0)
        {
            [SVProgressHUD showInfoWithStatus:baseModel.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        
        //请求数据"data"转模型
        self.redEnvelopeModel = [KRedEnvelopeModel mj_objectWithKeyValues:[responseBody valueForKey:@"data"]];
        [self.redEnveDataListModelArray addObjectsFromArray:self.redEnvelopeModel.DataList];
        
        for (KRedEnvelopeDataListModel *redEnveListModel in self.redEnveDataListModelArray) {
            self.webModel = [KBaseWebModel mj_objectWithKeyValues:redEnveListModel.web];
            [self.webModelArray addObject:self.webModel];
        }
        
        [self.mainTable reloadData];
        
    } failureBlock:^(NSString *error) {
        ErrorShow(error);
    }];
    
}

#pragma mark - 获取广告列表接口请求
-(void)loadDataWithAD{
    //POST /common/Common/GetAdvertList  获取广告列表
    [[NetworkSingleton sharedManager]POSTdata:nil Path:@"/common/Common/GetAdvertList" successBlock:^(id responseBody) {
        
        BaseModel *baseModel = [BaseModel mj_objectWithKeyValues:responseBody];
        if (baseModel.code != 0){
            [SVProgressHUD showInfoWithStatus:baseModel.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        
        BaseModel *baseModelInside = [BaseModel mj_objectWithKeyValues:baseModel.data];
        if (baseModelInside.code != 0){
            [SVProgressHUD showInfoWithStatus:baseModelInside.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        [SVProgressHUD dismiss];
        //请求数据"data"转模型
        self.redEnveDataListModelArray= [NSMutableArray array];
        [self.adListModelArray addObjectsFromArray:baseModelInside.data];
        self.adListModel = [KAdvertListModel mj_objectWithKeyValues:[responseBody valueForKey:@"data"]];
        self.webModel = [KBaseWebModel mj_objectWithKeyValues:self.adListModel.web];
        [self.mainTable reloadData];
    } failureBlock:^(NSString *error) {
        ErrorShow(error);
    }];
}

#pragma mark - 培训页接口请求
-(void)loadDataWithTrainingActivities{
    [SVProgressHUD show];
    NSDictionary *parameters = @{
                                 @"_appid" : @"103",
                                 @"_code" : [KUserLoginModel shareInstance].Code ? [KUserLoginModel shareInstance].Code : [KWXLoginUserListModel shareInstance].Code,
                                 @"sType": @"",//可不传
                                 @"Keyword":@"", //搜索框关键字
                                 @"PageIndex":@"1",
                                 @"PageSize":@"20"
                                 };
    [[NetworkSingleton sharedManager]POSTdata:parameters Path:@"activity/meeting/getmeetinglist" successBlock:^(id responseBody) {
        
        BaseModel *baseModel = [BaseModel mj_objectWithKeyValues:responseBody];
        if (baseModel.code != 0)
        {
            [SVProgressHUD showInfoWithStatus:baseModel.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        
        [SVProgressHUD dismiss];
        //请求数据"data"转模型
        self.trainActivitiesModel = [KTrainingActivitiesModel mj_objectWithKeyValues:[responseBody valueForKey:@"data"]];
        [self.trainActDataListModelArray addObjectsFromArray:self.trainActivitiesModel.DataList];
        for (KTrainingActivitiesDataListModel *trainingActListModel in self.trainActDataListModelArray) {
            self.webModel = [KBaseWebModel mj_objectWithKeyValues:trainingActListModel.web];
            [self.webModelArray addObject:self.webModel];
        }
        [self.mainTable reloadData];
    } failureBlock:^(NSString *error) {
        ErrorShow(error);
    }];
}

-(void)setUpUI{
    //添加到视图
    [self.view addSubview:self.navigationSelectView];
    [self.navigationSelectView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).mas_offset(20);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    [self.view addSubview:self.mainTable];
    [self.mainTable mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationSelectView.mas_bottom);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    
    [self.navigationSelectView.redEnvelopeActivityBtn addTarget:self action:@selector(OnRedEnvelopeActivityBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationSelectView.cultivateActivityBtn addTarget:self action:@selector(onCultivateActivityBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationSelectView.scratchRedEnvelopeBtn addTarget:self action:@selector(onScratchRedEnvelopeBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger totalCounnt = 0;
    switch (flag) {
        case 0:{ //红包
            totalCounnt = self.redEnveDataListModelArray.count;
        }break;

        case 1:{ // 培训
            totalCounnt = self.trainActDataListModelArray.count;
        }break;

        case 2:
        {

        }break;
    }
    
//    totalCounnt = self.trainActDataListModelArray.count;

    
    return totalCounnt;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"cell";

    KRedEnvelopeTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[KRedEnvelopeTableViewCell alloc] initWithTableView:tableView WithShowtype:KHomePageTableViewCellType_RedEnvelope reuseIdentifier:CellIdentifier];
        switch (flag) {
            case 0:{ //红包
                cell.tableCellType = KHomePageTableViewCellType_RedEnvelope;
                cell.redEnveDataListModel = self.redEnveDataListModelArray[indexPath.row];
                cell.redEnvelopeIcon.hidden = NO;
                cell.redEnvelopeLabel.hidden = NO;
            }break;
                
            case 1:{ // 培训
                cell.tableCellType = KHomePageTableViewCellType_Cultivate;
                cell.trainActDataListModel = self.trainActDataListModelArray[indexPath.row];
            }break;
                
            case 2:
            {
                
            }break;
                
            default:
                break;
        }
    }
    
    switch (flag) {
        case 0:{ //红包
            cell.tableCellType = KHomePageTableViewCellType_RedEnvelope;
            cell.redEnveDataListModel = self.redEnveDataListModelArray[indexPath.row];
            cell.redEnvelopeIcon.hidden = NO;
            cell.redEnvelopeLabel.hidden = NO;
        }break;
            
        case 1:{ // 培训
            cell.tableCellType = KHomePageTableViewCellType_Cultivate;
            cell.trainActDataListModel = self.trainActDataListModelArray[indexPath.row];
        }break;
            
        case 2:
        {
            
        }break;
            
        default:
            break;
    }
    
    return cell;
}

#pragma mark - UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}

//- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 172.5;
////    return CGFLOAT_MIN;
//}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    switch (flag) {
        case 0:{ //红包
            [self.headView.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.adListModelArray[0].Pic]] placeholderImage:[UIImage imageNamed:@"loading"]];
        }break;
            
        case 1:{ // 培训
            [self.headView.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.adListModelArray[1].Pic]] placeholderImage:[UIImage imageNamed:@"loading"]];
        }break;
            
        case 2:
        {
            [self.headView.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.adListModelArray[2].Pic]] placeholderImage:[UIImage imageNamed:@"loading"]];
        }break;
            
        default:
            break;
    }
    return self.headView;
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (flag) {
        case 0:{ //红包
            BaseWebViewController *sub = [[BaseWebViewController alloc] init];
//            NSString *urlString = [self.redEnveDataListModelArray[indexPath.row].web valueForKey:@"ClickUrl"];
            NSString *urlString = [self.webModelArray[indexPath.row] valueForKey:@"ClickUrl"];
            sub.urlStr = [NSString stringWithFormat:@"%@,%@",urlString,[KUserLoginModel shareInstance].Code ? [KUserLoginModel shareInstance].Code : [KWXLoginUserListModel shareInstance].Code];
            sub.title = [self.redEnveDataListModelArray[indexPath.row].web valueForKey:@"Title"];
            sub.hidesBottomBarWhenPushed = YES;
            [sub showCustomNavigationBackButton];
            [self.navigationController pushViewController:sub animated:YES];
        }break;
            
        case 1:{ // 培训
            BaseWebViewController *sub = [[BaseWebViewController alloc] init];
//            NSString *urlString = [self.trainActDataListModelArray[indexPath.row].web valueForKey:@"ClickUrl"];
            NSString *urlString = [self.webModelArray[indexPath.row] valueForKey:@"ClickUrl"];
            sub.urlStr = [NSString stringWithFormat:@"%@,%@",urlString,[KUserLoginModel shareInstance].Code ? [KUserLoginModel shareInstance].Code : [KWXLoginUserListModel shareInstance].Code];
            sub.title = [self.trainActDataListModelArray[indexPath.row].web valueForKey:@"Title"];
            sub.hidesBottomBarWhenPushed = YES;
            [sub showCustomNavigationBackButton];
            [self.navigationController pushViewController:sub animated:YES];
        }break;
            
        case 2:
        {
        }break;
            
        default:
            break;
    }
}

#pragma mark - 按钮点击方法
-(void)OnRedEnvelopeActivityBtnClick{
    flag = 0;
    //改变选择颜色
    [self.navigationSelectView.redEnvelopeActivityBtn setTitleColor:KColorOneAlpha(48,138,245) forState:UIControlStateNormal];
    [self.navigationSelectView.cultivateActivityBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.scratchRedEnvelopeBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.bgLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.navigationSelectView.redEnvelopeActivityBtn.mas_bottom);
        make.left.right.mas_equalTo(self.navigationSelectView.redEnvelopeActivityBtn);
        make.height.mas_equalTo(2);
    }];
    [self loadData];
    
}

-(void)onCultivateActivityBtnClick{
    flag = 1;
    //改变选择颜色
    [self.navigationSelectView.redEnvelopeActivityBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.cultivateActivityBtn setTitleColor:KColorOneAlpha(48,138,245) forState:UIControlStateNormal];
    [self.navigationSelectView.scratchRedEnvelopeBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.bgLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.navigationSelectView.cultivateActivityBtn.mas_bottom);
        make.left.right.mas_equalTo(self.navigationSelectView.cultivateActivityBtn);
        make.height.mas_equalTo(2);
    }];
    
    [self loadDataWithTrainingActivities];
}

-(void)onScratchRedEnvelopeBtnClick{
    
    flag = 2;
    //改变选择颜色
    [self.navigationSelectView.redEnvelopeActivityBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.cultivateActivityBtn setTitleColor:KColorOneAlpha(51,51,51) forState:UIControlStateNormal];
    [self.navigationSelectView.scratchRedEnvelopeBtn setTitleColor:KColorOneAlpha(48,138,245) forState:UIControlStateNormal];
    
    [self.navigationSelectView.bgLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.navigationSelectView.scratchRedEnvelopeBtn.mas_bottom);
        make.left.right.mas_equalTo(self.navigationSelectView.scratchRedEnvelopeBtn);
        make.height.mas_equalTo(2);
    }];
}

#pragma mark - getter
-(KNavigationSelectView *)navigationSelectView{
    if (!_navigationSelectView) {
        _navigationSelectView = [[KNavigationSelectView alloc] initwithNaviType:KNaviType_HomePage];
        _navigationSelectView.backgroundColor = KWhiteColor;
    }
    return _navigationSelectView;
}

-(UITableView *)mainTable{
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _mainTable.tableFooterView = [[UIView alloc] init];
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTable.delegate = self;
        _mainTable.dataSource = self;
        self.headView.frame = CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN);
        _mainTable.tableHeaderView = self.headView;
        
    }
    return _mainTable;
}

-(KBannerHeadTableViewCell *)headView{
    if (!_headView) {
        static NSString *CellId = @"headViewcell";
        _headView = [[KBannerHeadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
    }
    return _headView;
}

-(KRedEnvelopeModel *)redEnvelopeModel{
    if (!_redEnvelopeModel) {
        _redEnvelopeModel = [[KRedEnvelopeModel alloc] init];
    }
    return _redEnvelopeModel;
}

-(KTrainingActivitiesModel *)trainActivitiesModel{
    if (!_trainActivitiesModel) {
        _trainActivitiesModel = [[KTrainingActivitiesModel alloc] init];
    }
    return _trainActivitiesModel;
}

-(NSMutableArray<KRedEnvelopeDataListModel *> *)redEnveDataListModelArray{
    if (!_redEnveDataListModelArray) {
        _redEnveDataListModelArray = [[NSMutableArray alloc] init];
    }
    return _redEnveDataListModelArray;
}

-(NSMutableArray<KTrainingActivitiesDataListModel *> *)trainActDataListModelArray{
    if (!_trainActDataListModelArray) {
        _trainActDataListModelArray = [[NSMutableArray alloc] init];
    }
    return _trainActDataListModelArray;
}

-(NSMutableArray<KBaseWebModel *> *)webModelArray{
    if (_webModelArray) {
        _webModelArray = [[NSMutableArray alloc] init];
    }
    return _webModelArray;
}

@end
